package com.umeox.watch.moto.launcher.adapter;


import static com.umeox.watch.moto.launcher.ui.FragmentFactory.ITEM_ID;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 提供删除、更换Fragment功能
 */
public class HomePagerAdapter extends FragmentStateAdapter {
    public static final long DEFAULT_VALUE = Integer.MIN_VALUE;
    private List<Fragment> mFragments = new ArrayList<>();

    public HomePagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    public HomePagerAdapter(@NonNull Fragment fragment) {
        super(fragment);
    }


    public void setFragments(List<Fragment> fragments) {
        mFragments.clear();
        mFragments.addAll(fragments);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        final Fragment fragment = mFragments.get(position);
        return fragment;
    }

    @Override
    public int getItemCount() {
        return mFragments.size();
    }

    @Override
    public long getItemId(int position) {
        final Bundle arguments = mFragments.get(position).getArguments();
        if (arguments == null) {
            return DEFAULT_VALUE;
        }
        return arguments.getLong(ITEM_ID, DEFAULT_VALUE);
    }

    @Override
    public boolean containsItem(long itemId) {
        boolean contains = false;
        for (Fragment fragment : mFragments) {
            final Bundle arguments = fragment.getArguments();
            if (arguments == null) {
                continue;
            }
            if (arguments.getLong(ITEM_ID, DEFAULT_VALUE) == itemId) {
                contains = true;
                break;
            }
        }
        return contains;
    }
}
